library(tidyverse)
library(foreign)
library(haven)

cook <- read_dta("judgeyear_turnover_chicago.dta")

cook <- cook %>% arrange(c_judgeid, init_year)  %>%
  mutate(last_year = ifelse(lag(judge_name, default = "placeholder") == judge_name & lag(init_year, default = 0) == init_year - 1, 1, 0)) %>% 
  group_by(judge_name, flag = cumsum(last_year == 0)) %>% 
  mutate(bench_years = row_number()) %>% 
  ungroup %>% 
  select(-flag)

write_dta(data = cook, path = "judgeyear_turnover_chicago_recoded.dta")
